package com.bbcare.exportExcel.plat.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.bbcare.comm.*;
import com.bbcare.exportExcel.plat.utils.Asyn;
import com.bbcare.exportExcel.plat.utils.ExportUtils;
import com.bbcare.exportExcel.plat.vo.ExportResult;
import com.bbcare.exportExcel.plat.service.IExportService;


/**
 * 队列专案数据导出模块。
 * @author Michael Zhu(2022/06)
 */
@Controller
@RequestMapping("/export")
public class ExportController {
    private final static Log logger = LogFactory.getLog(ExportController.class);
    private static String DATE_FORMAT_DT10 = "yyyy-MM-dd";

    @Autowired
    Asyn asyn;  //多线程并发异步执行。
    @Autowired
    IExportService exportService;


    @ResponseBody
    @RequestMapping("/hello")
    public String hello()   {
        return "export_hello";
    }

    @ResponseBody
    @RequestMapping(value = "/start", method = RequestMethod.POST)
    public ResultModel<String> startup(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.info("++++startup()----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if(null == requestParam ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }

        String queueId  = requestParam.getString("queueId");
        if(null == queueId || queueId.isEmpty()){
            logger.error("++++startup() queueId is empty!");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，queueId不能为空");
        }
        if ("gzykdxfsdsyyMZqueue001".equals(queueId))   {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，临时门诊队列没有数据可以导出！");
        }

        final String startDate    = requestParam.getString("startDate");
        if(null == startDate || startDate.isEmpty()){
            logger.error("++++startup() startDate is empty!");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，startDate不能为空");
        }
        if (!ExportUtils.isLegalDate(startDate.length(), startDate, DATE_FORMAT_DT10))    {
            throw new RuntimeException("开始时间格式错误，正确格式是DT10,yyyy-MM-dd！！");
        }

        final String endDate    = requestParam.getString("endDate");
        if(null == endDate || endDate.isEmpty()){
            logger.error("++++startup() endDate is empty!");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，endDate不能为空");
        }
        if (!ExportUtils.isLegalDate(endDate.length(), endDate, DATE_FORMAT_DT10))    {
            throw new RuntimeException("结束时间格式错误，正确格式是DT10,yyyy-MM-dd！！");
        }

        String tenantId   = requestParam.getString("tenantId");
        String doctorId   = requestParam.getString("doctorId");
        if ((null == doctorId || doctorId.isEmpty()) && null != request) {
            Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
            if (null != sessionMap && sessionMap.size()>1) {
                tenantId = (String) sessionMap.get("tenantId");// 租户id
                doctorId = (String) sessionMap.get("authorId");// 医生ID
            }
        }
        if (null == doctorId || doctorId.isEmpty()) {
            logger.error("++++startup() doctorId is empty!");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，doctorId不能为空");
        }
        if (null == tenantId || tenantId.isEmpty()) {
            logger.error("++++startup() tenantId is empty!");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，tenantId不能为空");
        }

        asyn.startExport(tenantId, doctorId, queueId, startDate, endDate);

        return new ResultModel<String>("已开始导出操作，请到导出历史查询导出结果。");
    }

    /**
     * 查询导出结果。
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public ResultModel<List<ExportResult>> queryExportResult(HttpServletRequest request) throws Exception {
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String tenantId = "tenant_id";
        String doctorId = "doctor_id";
        if (null != sessionMap && sessionMap.size()>1) {
            tenantId = (String) sessionMap.get("tenantId");// 租户id
            doctorId = (String) sessionMap.get("authorId");// 医生ID
        }
        logger.info("++++queryExportResult() doctorId:" + doctorId+", tenantId:"+tenantId);
        final List<ExportResult> retList    = exportService.selectExportResults(doctorId);
        return new ResultModel<List<ExportResult>>(retList);
    }

    /**
     * 检查items参数中是否存在重复项。（items是JSON格式）
     * @param arg
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/check_duplicate", method = RequestMethod.POST)
    public ResultModel<Map<String,Object>> checkDuplicateItem(@RequestBody String arg) throws Exception {
        logger.info("++++checkDuplicateItem()----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
        if(null == requestParam ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String checkStr = requestParam.getString("items");
        if(null == checkStr || checkStr.isEmpty()){
            logger.error("++++checkDuplicateItem() items is empty!");
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，items不能为空");
        }

        Map<String,List<String>> dupMap = exportService.getQuestionFromJson(checkStr);
        final List<String> itemList   = dupMap.get("id");
        final List<String> nameList   = dupMap.get("name");
        Map<String,Object> dupItemMap   = ExportUtils.checkDuplicate(itemList);
        return new ResultModel(dupItemMap);
    }
}
